package ch.doublet.jw.pubdownloader;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class UrlDownloaderHelper {
	final static int size = 1024;

	public static void fileUrl(String urlAdresse, String localFileName,
			String destinationDir) {
		OutputStream outStream = null;
		URLConnection uCon = null;
		InputStream is = null;
		try {
			URL url;
			byte[] buf;
			int ByteRead, ByteWritten = 0;
			url = new URL(urlAdresse);
			new File(destinationDir).mkdirs();
			outStream = new BufferedOutputStream(new FileOutputStream(new File(
					destinationDir + localFileName)));

			uCon = url.openConnection();
			is = uCon.getInputStream();
			buf = new byte[size];
			while ((ByteRead = is.read(buf)) != -1) {
				outStream.write(buf, 0, ByteRead);
				ByteWritten += ByteRead;
			}
			printInformation(localFileName, url, ByteWritten);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
				if (outStream != null) {
					outStream.close();
				}
			} catch (IOException e) {
				// macht nix.
			}
		}
	}

	private static void printInformation(String localFileName, URL url,
			int ByteWritten) {
		System.out.println("Downloaded Successfully.");
		System.out.println("From : " + url.toString());
		System.out.println("File name:\"" + localFileName + "\"\nNo ofbytes :"
				+ ByteWritten);
	}

	public static void fileDownload(String fAddress, String destinationDir,
			String nome) {
		int slashIndex = fAddress.lastIndexOf('/');
		int periodIndex = fAddress.lastIndexOf('.');

		if (periodIndex >= 1 && slashIndex >= 0
				&& slashIndex < fAddress.length() - 1) {
			fileUrl(fAddress, nome, destinationDir);
		} else {
			System.err.println("path or file name.");
		}
	}

}
